<script setup lang='ts'>
import type { CurrencyCode } from '~/composables/useCurrencyData'
import AppGetRebateBonus from '~/components/AppGetRebateBonus.vue'

defineOptions({ name: 'AppRebateCenterBanner' })

defineProps<{ showRebateBtn: boolean }>()

const { currentGlobalCurrency } = storeToRefs(useAppStore())
// const { openRealTimeRebateDialog } = useDialogRealTimeRebate()
const {
  bool: amountLoading,
  setTrue: amountLoadingTrue,
  setFalse: amountLoadingFalse,
} = useBoolean(false)
const { open } = useDialog(AppGetRebateBonus, null, { showHeader: false, bgColor: 'var(--color-bg-black-4)' })
const expectAmount = ref(0)

const currentGlobalCurrencyCode = computed(() => getCurrencyConfig(currentGlobalCurrency.value).cur)

const { runAsync: runAsyncRebateSum } = useRequest(ApiMemberRebateSum, {
  onBefore() {
    amountLoadingTrue()
  },
  onSuccess(res) {
    if (res && res.length > 0) {
      // 相同币种的分组
      const allArr = res.reduce((acc, item) => {
        const currencyId = item.currency_id
        const rebate = Number.parseFloat(item.rebate_amount)

        if (!acc[currencyId])
          acc[currencyId] = 0

        acc[currencyId] += rebate

        return acc
      }, {} as Record<CurrencyCode, number>)

      const grouped = (Object.entries(allArr) as [CurrencyCode, number][]).map(([currency_id, total_rebate]) => ({
        currency_id,
        total_rebate,
      }))
      // 当前货币
      const arrCurrentCur = grouped.filter(a => a.currency_id === currentGlobalCurrencyCode.value)
      // 其他货币
      const arrExceptCurrentCur = grouped.filter(a => a.currency_id !== currentGlobalCurrencyCode.value)

      if (arrCurrentCur.length > 0)
        expectAmount.value = arrCurrentCur[0].total_rebate

      if (arrExceptCurrentCur.length > 0) {
        const arrPromise = arrExceptCurrentCur.map((a) => {
          return getRateAndCalculate(a)
        })

        Promise.allSettled(arrPromise).then((result) => {
          const arr = result.filter(a => a.status === 'fulfilled').map(a => a.value)
          const total = arr.reduce((acc, item) => {
            return Number.parseFloat(add(acc, item))
          }, 0)

          expectAmount.value = Number.parseFloat(add(expectAmount.value, total))
          amountLoadingFalse()
        })
      }
      else {
        amountLoadingFalse()
      }
    }
    else {
      amountLoadingFalse()
    }
  },
})

// 领取返水
function rebateHandler() {
  open({
    openGetBonusDialog: open
  })
//   openRealTimeRebateDialog()
}
// 获取汇率并计算返水
function getRateAndCalculate(item: {
  currency_id: CurrencyCode
  total_rebate: number
}) {
  return new Promise<number>((resolve) => {
    ApiExchangeRateFromTo({ from: item.currency_id, to: currentGlobalCurrencyCode.value }).then((rateData) => {
      const amount = Number.parseFloat(mul(item.total_rebate, Number.parseFloat(rateData[item.currency_id])))
      resolve(amount)
    }).catch(() => {
      resolve(0)
    })
  })
}

runAsyncRebateSum()
</script>

<template>
  <!-- 默认 -->
  <div class="default-card">
    <div class="flex items-center">
      <div class="mr-4 w-15">
        <BaseImage url="/images/webp/vip/vip-rebate.webp" />
      </div>
      <div>
        <h6>
          {{ $t('vip_expect_rebate') }}
        </h6>
        <div class="h-6 flex items-center text-text-white-2">
          <AppAmount :amount="expectAmount" :currency-type="currentGlobalCurrency" />
        </div>
      </div>
    </div>
    <BaseButton v-if="showRebateBtn" class="mt-3 h-10 font-semibold text-xs" bg-style="secondary" @click="rebateHandler">
      {{ $t('vip_get_rebates') }}
    </BaseButton>
  </div>
</template>

<style lang='scss' scoped>
.default-card {
  --bc-amount-currency-size: 1rem;
  width: 100%;
  border-radius: 10px;
  background: linear-gradient(91deg, rgba(149, 255, 236, 0.00) 0%, rgba(149, 255, 236, 0.00) 0.53%, rgba(115, 175, 168, 0.20) 98.76%), #323738;
  color: var(--color-text-white-0);;
  font-size: 14px;
  font-weight: 500;
  line-height: 20px;
  display: flex;
  flex-direction: column;
  padding: 1rem 0.625rem;
  h6 {
    color: var(--color-text-white-0);
  }
}
</style>
